package exam.test;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.List;

import static exam.test.SocketServerListenHandler.clientSockets;

@Component
public class SocketServerClientHandler extends Thread{

    private static MyWebSocketServer webSocketServer;
    //private final List<Socket> allSockets; // 新增：保存所有连接的Socket引用
    @Autowired
    public SocketServerClientHandler(MyWebSocketServer webSocketServer) {
        this.webSocketServer = webSocketServer;
    }

    //每个消息通过Socket进行传输
    private Socket clientConnectSocket;
    public SocketServerClientHandler(Socket clientConnectSocket){
        this.clientConnectSocket = clientConnectSocket;
    }

    @Override
    public void run(){
        try {
            InputStream inputStream = clientConnectSocket.getInputStream();
            while (true) {
                byte[] data = new byte[100];
                int len;
                while ((len = inputStream.read(data)) != -1) {
                    String message = new String(data, 0, len);
                    System.out.println("客户端传来消息: " + message);
                    clientConnectSocket.getOutputStream().write(data);
                    sendMessageToWebsocket(message);
                    sendMessageToOtherClients(message,clientConnectSocket);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }/*finally{
            try {
                clientConnectSocket.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            SocketServerListenHandler.removeDisconnectedClient(clientConnectSocket);
        }
        */

    }

    // 处理后端消息并发送给前端
    public static void sendMessageToWebsocket(String message) {
        if (webSocketServer != null) {
            webSocketServer.sendMessageToClients(message);
        }
    }

    // 向除当前Socket外的所有客户端发送消息
    private void sendMessageToOtherClients(String message, Socket excludeSocket) {
        for (Socket socket : clientSockets) {
            if (socket != excludeSocket && socket.isConnected()) {
                try {
                    OutputStream outputStream = socket.getOutputStream();
                    outputStream.write(message.getBytes());
                } catch (IOException e) {
                    System.err.println("发送消息到其他客户端时出错：" + e.getMessage());
                }
            }
        }
    }
}
